﻿; (function () {
    'use strict';
    String.prototype.formatWith = function () {
        var args = arguments, self = this;
        for (var i = 0, len = args.length; i < len; i++) {
            self = self.replace(new RegExp('\\{' + i + '\\}', 'g'), args[i]);
        }
        return self;
    };
    var api = {};

    api.parseUrl = function (url) {
        var data = {
            source: url
        };
        var reg = /^(\w+):\/\/([\w\.]+)(:\d+)?\/?()(\?[^#]*)?(#.*)?$/;
        var match = url.match(reg);
        console.log(match);
        return data;
    };

    /*返回url信息 兼容IE7*/
    api.getUrlInfo = function (url, loc) {
        var a = document.createElement('a');
        loc = loc || location;
        try {
            var newUrl = url;
            if (/^\w+\:\/\//.test(url)) {
                /*绝对地址*/
            } else if (url.indexOf('../') == 0) {
                var paths = loc.pathname.replace(/^\/+/, '').split(/\/+/).slice(0, -1);
                var matchs = url.match(/^(\.\.\/)+/);
                if (matchs) {
                    var len = matchs[0].split('../').length - 1;
                    var abPath = "/" + paths.slice(0, paths.length - len).join('/') + '/';
                    newUrl = url.replace(/^(\.\.\/)+/g, abPath.replace(/^\/+/, '/'));
                }
            } else if (url.indexOf('//') == 0) {
                newUrl = loc.protocol + url;
            } else if (url.indexOf('/') == 0) {
                /*绝对地址*/
            } else {
                var path = '/' + loc.pathname.replace(/^\/+/, '').split(/\/+/).slice(0, -1).join('/') + '/';
                newUrl = path.replace(/^\/+/, '/') + url;
            }
            a.href = newUrl;
            var pathname = '/' + a.pathname.replace(/^\/+/, '');
            var data = {
                source: url,
                href: a.href,
                protocol: a.protocol.replace(':', ''),
                host: a.hostname,
                port: a.port,
                search: a.search,
                file: (pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
                hash: a.hash,
                pathname: a.pathname,
                path: pathname
            };
            if (!data.host) {
                data.protocol = loc.protocol.replace(':', '');
                data.host = loc.hostname;
                data.port = loc.port;
            }
            var fullPath = data.protocol + '://' + data.host;
            if (data.port == '80' && data.protocol == 'http') {

            } else if (data.port == '443' && data.protocol == 'https') {

            } else if (data.port) {
                fullPath += ':' + data.port;
            }
            fullPath += data.path;
            data.fullPath = fullPath;
            return data;
        } catch (e) {
            console.error(e);
        }
    };

    window.UrlLib = api;
})();